﻿#!/usr/bin/python3

#pip3 install xlrd==1.2.0
import xlrd
import time

import os
import sys
import getopt

import json


default_json = '{"configurations":[{"intelliSenseMode":"clang-x64","name":"Win32","cppStandard":"c++11","cStandard":"c99","compilerPath":"","includePath":[],"defines":[]}]}'


def scan_dir(path):
    inc_path = []
    print("scan: " + path)
    for root, dirs, files in os.walk(path):
        #print('root: '+ str(root) )
        #print('sdirs: '+ str(dirs) )
        #print('files: '+ str(files) )
        #先查找当前文件夹是否有.h文件
        for name in files:
            filepath = str(os.path.join(root, name))
            if filepath.endswith(tuple(["h"])):
                print("append path: " + root)
                inc_path.append(root)
                break
    return inc_path


def main(argv):
    inputfile = ''
    outputfile = ''
    projectdir = ''
    try:
        opts, args = getopt.getopt(argv,"hi:o:d:",["ifile=","ofile=","dir="])
    except getopt.GetoptError:
        print(' -i <inputfile> -o <outputfile> -d <project dir>')
        sys.exit(2)
    for opt, arg in opts:
        if opt == '-h':
            print(' -i <inputfile> -o <outputfile> -d <project dir>')
            sys.exit()
        elif opt in ("-i", "--ifile"):
            inputfile = arg
        elif opt in ("-o", "--ofile"):
            outputfile = arg
        elif opt in ("-d", "--dir"):
            projectdir = arg
            
    print('输入的文件为：', inputfile)
    print('输出的文件为：', outputfile)
    print('项目文件夹：', projectdir)

    print("Hello, World! 123")
    inc_path = scan_dir(projectdir)
    
    print("Hello, World! 456")
    for item in inc_path:
        print(item)

    print("Hello, World! 789")
    
    if os.path.exists(inputfile):
        json_in_file = open(inputfile, 'r')
        json_in_str = json_in_file.read()
        json_in_file.close()
    else :
        json_in_str = default_json
        json_in_file = open(inputfile, 'w')
        json_in_file.write( json.dumps(json.loads(json_in_str), indent=4 ) )
        json_in_file.close()

    json_in_obj = json.loads(json_in_str)
    
    
    print(str(json_in_obj['configurations'][0]['includePath'] ))
    
    for item in inc_path:
        json_in_obj['configurations'][0]['includePath'].append(item)
    
    print(str(json_in_obj['configurations'][0]['includePath'] ))
    
    json_out_str = json.dumps(json_in_obj, indent=4)
    
    
    json_out_file = open(outputfile, 'w')
    
    json_out_file.write(json_out_str)
    
    json_out_file.close()
    

if __name__ == "__main__":
   main(sys.argv[1:])
   
   
   